package com.tanhua.dubbo.server.service;

import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * @param userId
     * @param publishId
     * @return 目标:将自己发布的动态写入所有好友的时间线表
     * 1.拿到发布者所有好友的id,表tanhua_user记录了发布者id与发布者好友id
     */
    @Async //异步执行，原理：底层开一个线程去执行该方法
    public CompletableFuture<String> saveTimeLine(Long userId, ObjectId publishId) {
        try {
            Query query = new Query(Criteria.where("userId").is(userId));
            /**
             *  *该集合存的是tanhua_user中"userId"==发布者id的诸行信息
             */
            List<Users> users = mongoTemplate.find(query, Users.class);
            for (Users user : users) {
                TimeLine timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());
                timeLine.setPublishId(publishId);
                timeLine.setUserId(userId);
                timeLine.setDate(System.currentTimeMillis());
                mongoTemplate.save(timeLine, "quanzi_time_line_" + user.getFriendId());
            }
        } catch (Exception e) {
            log.error("写入好友时间线表失败~ userId = " + userId + ", publishId = " + publishId, e);
            //TODO 事务回滚问题
            return CompletableFuture.completedFuture("error");
        }

        return CompletableFuture.completedFuture("ok");
    }
}
